package demo.bignumb;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

public class ListCounter {

	private static List dataPrepair(int listSize) {
		List<Integer> list = new ArrayList<Integer>(listSize);
		for (int i = 0; i < listSize; i++) {
			list.add(i);
		}
		return list;
	}

	public static void main(String[] args) throws Exception {
		int threadNum = Runtime.getRuntime().availableProcessors();
		int listSize = 50000000;
		final List<Integer> list = dataPrepair(listSize);
		int threadListSize = listSize / threadNum;
		assert listSize > threadNum;
		final int[] dataRange = new int[threadNum];
		for (int i = 0; i < threadNum - 1; i++) {
			dataRange[i] = threadListSize * (i + 1);
		}
		dataRange[threadNum - 1] = listSize;
		ExecutorService executor = Executors.newFixedThreadPool(threadNum);
		Future<Long>[] results = new Future[threadNum];
		for (int i = 0; i < threadNum; i++) {
			results[i] = executor.submit(new CounterTask(dataRange[i]
					- threadListSize, dataRange[i], list));
		}
		long total = 0l;
		for (int i = 0; i < threadNum; i++) {
			total += results[i].get();
		}
		System.out.println("the list total sum:" + total);
		executor.shutdown();

	}

	private static class CounterTask implements Callable<Long> {
		final private int lowerLimit;
		final private int upperLimit;
		final private List<Integer> list;

		public CounterTask(int lowerLimit, int upperLimit,
				List<Integer> counteredList) {
			this.lowerLimit = lowerLimit;
			this.upperLimit = upperLimit;
			this.list = counteredList;
		}

		public Long call() throws Exception {
			long total = 0;
			for (int i = lowerLimit; i < upperLimit; i++) {
				total += list.get(i);
			}
			return total;
		}

	}

}
